import React, { useState, useRef } from 'react';
import { Modal, Button, Popconfirm } from 'antd';
import PatientInfo from './PatientInfo';
import ItemInfo from './ItemInfo';
import SettleInfo from './SettlementInfo';
import { showMsg, formatDate, MsgType } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import './style.less';

const Rent: React.FC<any> = (props) => {
  const { 
    actionRef,
    title,
    rentType,
    handleModalVisible,
    optCallback,
    handleRent } = props;

  // 患者信息
  const [info, setInfo] = useState<ORDERAPI.PatientHospitalInfo[]>([]);
  // 商品信息
  const [items, setItems] = useState<any[]>([]);

  const goodsRef = useRef(); // 获取物品信息的实例

  const [submitLoading, setSubmitLoading] = useState<boolean>(false);

  return (
    <Modal 
      width="90%"
      bodyStyle={{ height: window.innerHeight-185, overflowY: 'scroll' }}
      maskClosable={false}
      title={title}
      className="rent-dialog"
      onCancel={() => handleModalVisible(false)}
      footer={
        [
          <Button key="cancel" style={{marginRight: 10}} onClick={() => {
            handleModalVisible(false);
          }}>取消</Button>,
          
          rentType === 1 ? <PermissionControl  key="save" action_id="400402001">
              <Popconfirm 
                placement="topRight"
                title={`即将保存${info.length}位患者的租赁记录，确认保存？`}
                okText="确认保存"
                disabled={!info.length || !items.length}
                cancelText="再想想"
                onConfirm={async () => {
                  let data = {
                    detail_list: items.map(item => {
                      return {
                        ...item,
                        register_time: formatDate(item.register_time)
                      }
                    }),
                    // 患者信息
                    order_rent_list: info
                  }

                  if (!data.order_rent_list.length) {
                    showMsg('请选择患者信息', MsgType.INFO);
                    return;
                  }

                  if (!data.detail_list.length) {
                    showMsg('请添加物品信息', MsgType.INFO);
                    return;
                  }
                  console.log(data);
                  const success = await handleRent(data);
                  if (success) {
                    handleModalVisible(false);
                    actionRef.current.reload();
                  }
                  // 验证表格信息是否填写完整
                  // goodsRef.current.validate().then(async res => {
                  //   console.log('result', res)
                  //   if (!res) { return }
                  //   // const items = goodsRef.current.getData();
                  //   // console.log('items', items);
                  //   // console.log('form', goodsRef.current.getForm())
                  //   const items = goodsRef.current.getForm();

                  //   const detaillist = [];
                    
                  //   // eslint-disable-next-line no-restricted-syntax
                  //   for (const key in items) {
                  //     if (Object.prototype.hasOwnProperty.call(items, key)) {
                  //       const element = items[key];
                  //       element.register_time = formatDate(element.register_time);
                  //       detaillist.push(element);
                  //     }
                  //   }
                  // });
                }}>
                <Button type="primary" onClick={() => {
                  if (!info.length) {
                    showMsg('请选择患者信息', MsgType.INFO);
                    return;
                  }
                  if (!items.length) {
                    showMsg('请添加物品信息', MsgType.INFO);
                    return;
                  }
                  // @ts-ignore
                  if (goodsRef?.current?.editableKeys.length > 0) {
                    showMsg('您还有未保存的物品信息，请先保存', MsgType.INFO);
                    return;
                  }
                }}>
                  保存租赁记录
                </Button>
              </Popconfirm> 
            </PermissionControl> : <Button key="pay" loading={submitLoading} type="primary" onClick={async () => {
            if (!info.length) {
              showMsg('请选择患者信息', MsgType.INFO);
              return;
            }

            if (!items.length) {
              showMsg('请添加物品信息', MsgType.INFO);
              return;
            }

            // @ts-ignore
            if (goodsRef?.current?.editableKeys.length > 0) {
              showMsg('您还有未保存的物品信息，请先保存', MsgType.INFO);
              return;
            }

            let data = {
              detail_list: items.map(item => {
                return {
                  ...item,
                  register_time: formatDate(item.register_time)
                }
              }),

              // 患者信息
              ...info[0]
            }
            console.log(data);
            // if (submitLoading) {
            //   return;
            // }
            // setSubmitLoading(true);
            optCallback?.(data);
            // const success = await handleRent(data);
            // setSubmitLoading(false);
            // handleModalVisible(false);
            // if (success) {
            //   handleModalVisible(false);
            //   actionRef.current.reload();
            // }
          }}>提交支付</Button>
        ]
      }
      visible>
        <PatientInfo 
        rentType={rentType}
        onChange={(infos: ORDERAPI.PatientHospitalInfo[]) => {
          setInfo(infos);
        }}/>

        <ItemInfo ref={goodsRef} onChange={setItems} />

        {
          rentType === 2 && <SettleInfo goods={items} />
        }
    </Modal>
  );
};
export default Rent;
